package com.qianhai.manage.util;

import java.util.LinkedList;
import java.util.List;
import java.util.Random;
import java.util.regex.Pattern;

import org.apache.axis.encoding.Base64;

public class StringUtil {
	
	/**
	 * 如果字符串为空,则返回%;若不为空,则前后加上%
	 */
	public static String addPercent(String str) {
		if (str == null || "".equals(str.trim())) {
			str = "%";
		} 
		else {
			str="%"+str+"%";
		}
		return str;
	}
	
	/**
	 * 如果字符串为空,则返回%;若运算符为like,则前后加上%
	 */
	public static String addPercent(String str,String ysf) {
		if (str == null || "".equals(str.trim())) {
			str = "%";
		} 
		else if("like".equals(ysf)){
			str="%"+str+"%";
		}
		return str;
	}
	
	/**
	 * 如果字符串为空,则给一个默认值
	 */
	public static String addDefault(String str, String defaultstr) {
		if (str == null || "".equals(str.trim())) {
			return defaultstr;
		} 
		return str;
	}
	
	/**
	 * 如果字符串包含NULL,则返回空
	 */
	public static String replaceNull(String str) {
		if (str == null || str.indexOf("NULL")>=0) {
			return "";
		} 
		return str;
	}
	
	/**
	 * 如果字符串包含NULL,则返回空
	 */
	public static String replaceNullToZero(String str) {
		if (str == null ||"".equals(str.trim())|| str.indexOf("NULL")>=0) {
			return "0";
		} 
		return str;
	}
	
	/**
	 * 转换编码
	 */
	public static String ChangeEncoding(String str) {
		//判断是否存在乱码
		try { 
		if (str!=null&&!str.equals(new String(str.getBytes("GBK"), "GBK"))) { 
				return new String(str.getBytes("ISO-8859-1"), "UTF-8");
			} 
	 } catch (Exception e) {    
     }  
		return str;
	}
	
	public static String ChangeEncoding(String str,String CharSet) {
		try { 
			return new String(str.getBytes(CharSet));
	 } catch (Exception e) {    
     }  
		return str;
	}
	
	public static String ChangeEncoding(String str,String SrcCharset,String TargetCharSet) {
		try { 
			return new String(str.getBytes(SrcCharset),TargetCharSet);
	 } catch (Exception e) {    
     }  
		return str;
	}
	
	 /**
	 * 数组去重复
	 */
	 public static String[] array_unique(String[] a) {
	     List<String> list = new LinkedList<String>();
	     for(int i = 0; i < a.length; i++) {
	         if(!list.contains(a[i])) {
	             list.add(a[i]);
	         }
	     }
	     return (String[])list.toArray(new String[list.size()]);
	 }
	 
	/**
	* 生成随机字符串
	*/
	 public static String getRandomString(int length) { 
		    String base = "abcdefghijklmnopqrstuvwxyz0123456789";
		    Random random = new Random();   
		    StringBuffer sb = new StringBuffer();   
		    for (int i = 0; i < length; i++) {   
		        int number = random.nextInt(base.length());   
		        sb.append(base.charAt(number));   
		    }   
		    return sb.toString();   
		 }
	 
	/**
	* 生成随机数字
	*/
	 public static String getRandomNumber(int length) { 
		    String base = "0123456789";
		    Random random = new Random();   
		    StringBuffer sb = new StringBuffer();   
		    for (int i = 0; i < length; i++) {   
		        int number = random.nextInt(base.length());   
		        sb.append(base.charAt(number));   
		    }   
		    return sb.toString();   
		 }
	
	/**
	* 获得验证码（有规律）
	*/
	 public static String getCheckcode(String filename) { 
		 int a=Integer.parseInt(filename.substring(0,1));
		 int b=Integer.parseInt(filename.substring(1,2));
		 int c=Integer.parseInt(filename.substring(2,3));
		 int d=Integer.parseInt(filename.substring(3,4));
		 a=a-1;
		 if(a<0)
			 a=a+10;
		 b=b-2;
		 if(b<0)
			 b=b+10;
		 c=c-3;
		 if(c<0)
			 c=c+10;
		 d=d-4;
		 if(d<0)
			 d=d+10;
		    return String.valueOf(a)+String.valueOf(b)+String.valueOf(c)+String.valueOf(d);   
		 }
	 
	 
	/**
	*BASE64 编码 
	*/
	public static String getBASE64(byte[] bytes) { 
		if (bytes == null) 
			return null; 
		return Base64.encode(bytes);
		} 
	
	/**
	* BASE64 解码 
	*/
	public static byte[] getFromBASE64(String s) {
	if (s == null)
		return null; 
	try { 
	return Base64.decode(s); 
	} catch (Exception e) { 
		return null; 
		} 
	}

	/**
	* 保留小数
	*/
	public static String DecimalFormat(double d,int i) {
		return String.format("%."+i+"f", d);
	}
	
	/**
	* 统计字节数
	*/
	public static int countWords(String s) {
	  if(s==null)
		 return 0;
	  int length = 0;
        for(int i = 0; i < s.length(); i++)
        {
            int ascii = Character.codePointAt(s, i);
            if(ascii >= 0 && ascii <=255)
                length++;
            else
                length += 2;
        }
        return length;
    }
	
	/**
	* 判断是否为数字
	*/
	public static boolean isNumeric(String str){ 
		 Pattern pattern = Pattern.compile("-?[0-9]+.?[0-9]*"); 
		 return pattern.matcher(str).matches(); 
	 }
	
	/**
	 * 把中文转成Unicode码
	 */
	public static String chinaToUnicode(String str){
		String result="";
		for (int i = 0; i < str.length(); i++){
            int chr1 = (char) str.charAt(i);
            if(chr1>=19968&&chr1<=171941){//汉字范围 \u4e00-\u9fa5 (中文)
                result+="\\u" + Integer.toHexString(chr1);
            }else{
            	result+=str.charAt(i);
            }
        }
		return result;
	}
	
	/**
	 * 把Unicode码还原为中文
	 */
	public static String ascii2Native(String str) {
		StringBuilder sb = new StringBuilder();
		int begin = 0;
		int index = str.indexOf("\\u");
		while (index != -1) {
			sb.append(str.substring(begin, index));
			sb.append(ascii2Char(str.substring(index, index + 6)));
			begin = index + 6;
			index = str.indexOf("\\u", begin);
		}
		sb.append(str.substring(begin));
		return sb.toString();
	}
	
	private static char ascii2Char(String str) {
		if (str.length() != 6) {
			throw new IllegalArgumentException(
					"Ascii string of a native character must be 6 character.");
		}
		if (!"\\u".equals(str.substring(0, 2))) {
			throw new IllegalArgumentException(
					"Ascii string of a native character must start with \"\\u\".");
		}
		String tmp = str.substring(2, 4);
		int code = Integer.parseInt(tmp, 16) << 8;
		tmp = str.substring(4, 6);
		code += Integer.parseInt(tmp, 16);
		return (char) code;
	}
	
	public static boolean isEmpty(String str) {
		if(null == str || "".equals(str.trim())) {
			return true;
		}
		return false;
	}
	
	public static String getSuffix(String filePath) {
		String suffix = "";
		if(filePath.contains(".")) {
			suffix = filePath.substring(filePath.lastIndexOf(".") + 1);
		}
		return suffix;
	}

	
}
